using System.Collections.Generic;
using DotNetNuke.Common.Utilities;

namespace Code5Systems.FormMaster.Business
{

	public class FormMappingController
	{
		
#region Public Methods
		
		
		public List<FormMappingInfo> GetByForm(int formID)
		{
			
			return CBO.FillCollection<FormMappingInfo>(Code5Systems.FormMaster.Data.DataProvider.Instance().GetFormMappingByForm(formID));
			
		}
		
		public List<FormMappingInfo> GetByPage(int formID, int pageNum)
		{
			
			return CBO.FillCollection<FormMappingInfo>(Code5Systems.FormMaster.Data.DataProvider.Instance().GetFormMappingByPage(formID, pageNum));
			
		}
		
		public List<FormMappingInfo> GetByFormGeneric(int formID)
		{
			List<FormMappingInfo> mapList = new List<FormMappingInfo>();
			foreach (FormMappingInfo item in GetByForm(formID))
			{
				mapList.Add(item);
			}
			return mapList;
		}
		
		public void Add(List<FormMappingInfo> mappings, int pageNum = -1)
		{
			
			FormMappingInfo mapping = mappings[0];
			if (pageNum > 0)
			{
				DeleteByPage(mapping.FormID, pageNum);
			}
			else
			{
				Delete(mapping.FormID);
			}
			
			foreach (FormMappingInfo objFormMapping in mappings)
			{
				Code5Systems.FormMaster.Data.DataProvider.Instance().AddFormMapping(objFormMapping.FormID, objFormMapping.FormField, objFormMapping.TableField, objFormMapping.DataType, objFormMapping.Length, objFormMapping.Prec, objFormMapping.Scale, (objFormMapping.Nullable).ToString(), objFormMapping.PageNum);
			}
			
		}
		
		
		public void Delete(int formId)
		{
			
			Code5Systems.FormMaster.Data.DataProvider.Instance().DeleteFormMappings(formId);
			
		}
		
		public void DeleteByPage(int formId, int pageNum)
		{
			
			Code5Systems.FormMaster.Data.DataProvider.Instance().DeleteFormMappingsByPage(formId, pageNum);
			
		}
		
		public void CreateTableFromForm(string createScript, List<FormMappingInfo> mappings, FormController formCtl, int moduleId)
		{
			
			if (formCtl.FormInfo.ExtTableForEachPage)
			{
				Code5Systems.FormMaster.Data.DataProvider.Instance().ExecuteSQL(formCtl.FormInfo.CurrentPage.ExtTableConnStr, createScript);
				Add(mappings, formCtl.FormInfo.CurrentPage.PageNum);
			}
			else
			{
				Code5Systems.FormMaster.Data.DataProvider.Instance().ExecuteSQL(formCtl.FormInfo.ExtTableConnStr, createScript);
				Add(mappings);
			}
			
			FormController objFormCtl = new FormController(moduleId);
			objFormCtl.Update(formCtl.FormInfo);
		}
#endregion
		
	}
	
}

